package com.kchouse.mine;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kchouse.MainActivity;
import com.kchouse.R;
import com.kchouse.bean.MinePrestoreItem;
import com.kchouse.bean.OrderEvaItem;
import com.kchouse.bean.PrestoreRecordItem;
import com.kchouse.common.API;
import com.kchouse.common.BaseActivity;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.ToastUtils;
import com.kchouse.view.BannerLoader;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import java.util.ArrayList;
import java.util.List;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

public class MineprestoreActivity extends BaseActivity implements View.OnClickListener {

    private MineprestoreActivity mContent;
    private TextView tv_title;
    private ImageView iv_back;
    private ListView lv_item;
    private TextView tv_totalPoint;
    private int totalPoint;
    private ArrayList<MinePrestoreItem> listprestore = new ArrayList<>();
    private ArrayList<PrestoreRecordItem> listprestorepush = new ArrayList<>();
    private LvAdapter prestoreAdapter;
    private Intent intent;
    private ViewPager vp_item;
    private Handler handler = new Handler();

    private ArrayList<View> viewList = new ArrayList();
    private MyPagerAdapter pagerAdapter;
    private timerrunnable runtier;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_integral);

        mContent = this;
        intiData();
        intiView();
    }

    private void intiView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("我的预存");
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);

        tv_totalPoint = (TextView) findViewById(R.id.tv_totalPoint);
        lv_item = (ListView) findViewById(R.id.lv_item);
        lv_item.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MinePrestoreItem item = listprestore.get(position);
                intent.putExtra("totalPoint", totalPoint);
                intent.putExtra("MerchantShortName", item.getMerchantShortName());
                intent.putExtra("merchantId", item.getMerchantId());
                intent.setClass(mContent, MineprestoreDetailsActivity.class);
                startActivity(intent);

            }
        });

        prestoreAdapter = new LvAdapter();
        lv_item.setAdapter(prestoreAdapter);

        vp_item = (ViewPager) findViewById(R.id.vp_item);

        pagerAdapter = new MyPagerAdapter();
        vp_item.setAdapter(pagerAdapter);


    }

    class MyPagerAdapter extends PagerAdapter {

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public int getCount() {

            if (listprestorepush.size() > 1) {
                return viewList.size() * 10000;

            } else {
                return viewList.size();
            }
        }

        @Override
        public void destroyItem(ViewGroup container, int position,
                                Object object) {

//                container.removeView(viewList.get(0));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
//            container.addView(viewList.get(position));
//            return viewList.get(position);

            if (listprestorepush.size() > 1) {
                try {
                    container.addView(viewList.get(position % viewList.size()));
                } catch (Exception e) {

                }
                return viewList.get(position % viewList.size());
            } else {
                container.addView(viewList.get(position));
                return viewList.get(position);
            }


        }
    }


    class LvAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return listprestore.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            MinePrestoreItem item = listprestore.get(position);
            View view = getLayoutInflater().inflate(R.layout.lv_prestore_item, null);
            TextView tv_merchantName = (TextView) view.findViewById(R.id.tv_merchantName);
            tv_merchantName.setText(item.getMerchantShortName());
            TextView tv_remainPoint = (TextView) view.findViewById(R.id.tv_remainPoint);
            tv_remainPoint.setText("剩余预存:" + item.getRemainPoint());
            return view;
        }
    }

    private void intiData() {
        intent = getIntent();
        GetMineprestore();
        Getprestorepush();

    }

    /**
     * 预存推送列表
     */
    private void Getprestorepush() {
        String url = API.GetPrestorepush + MainActivity.userid;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("userId", MainActivity.userid);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    listprestorepush.clear();
                    listprestorepush.addAll(JSONObject.parseArray(json.getString("data"), PrestoreRecordItem.class));

                    intiPush();
                    pagerAdapter.notifyDataSetChanged();

                    if (listprestorepush.size() > 1) {
                        runtier = new timerrunnable();
                        handler.postDelayed(runtier, 5000);
                    }
                    if (listprestorepush.size() == 0) {
                        vp_item.setVisibility(View.GONE);
                    } else {
                        vp_item.setVisibility(View.VISIBLE);
                    }
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

    class timerrunnable implements Runnable {

        public void run() {
            int curitem = vp_item.getCurrentItem();
            vp_item.setCurrentItem(curitem + 1);
            if (handler != null) {
                handler.postDelayed(this, 5000);
            }
            Log.e("####", "curitem" + (curitem + 1));
        }
    }

    /**
     * 初始化推送
     */
    private void intiPush() {
        viewList.clear();
        for (int i = 0; i < listprestorepush.size(); i++) {
            PrestoreRecordItem item = listprestorepush.get(i);
            View view = getLayoutInflater().inflate(R.layout.lv_prestorepush_item, null);
            TextView tv_detail = (TextView) view.findViewById(R.id.tv_detail);
            TextView tv_merchantShortName = (TextView) view.findViewById(R.id.tv_merchantShortName);
            tv_merchantShortName.setText(item.getMerchantShortName());
            tv_detail.setText(item.getDetail() + " : " + item.getPoint());
            TextView tv_ok = (TextView) view.findViewById(R.id.tv_ok);
            tv_ok.setOnClickListener(new ConfirmOnClick(item.getId(), item.getDetail() + "，使用预存值： " + item.getPoint()));
            TextView tv_carNumber = (TextView) view.findViewById(R.id.tv_carNumber);
            if (TextUtils.isEmpty(item.getCarNumber())) {
                tv_carNumber.setVisibility(View.GONE);
            } else {
                tv_carNumber.setText(item.getCarNumber());
            }
            viewList.add(view);
        }
        Log.e("####", "viewListSize:" + viewList.size());
    }

    class ConfirmOnClick implements View.OnClickListener {

        private String recordId;
        private String context;

        public ConfirmOnClick(String recordId, String context) {
            this.recordId = recordId;
            this.context = context;
        }

        @Override
        public void onClick(View v) {
            showdialog_ok(recordId, context);
        }
    }

    public void showdialog_ok(final String recordId, String context) {

        final AlertDialog myDialog = new AlertDialog.Builder(mContent).create();
        myDialog.show();

        final Window view = myDialog.getWindow();
        myDialog.getWindow().setContentView(R.layout.mydialog);
        TextView tv_context = (TextView) view.findViewById(R.id.tv_context);
        tv_context.setText(context);
        TextView tv_cancel = (TextView) view.findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myDialog.dismiss();
            }
        });
        TextView tv_ok = (TextView) view.findViewById(R.id.tv_ok);
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                PostConfirmPush(recordId);
                myDialog.dismiss();
            }
        });
    }


    /**
     * 车主确认预存消费
     */
    private void PostConfirmPush(final String recordId) {
        String url = API.PostConfirmPush + recordId;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("recordId", recordId);

        HttpRequest.post(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
//                    String datastr = json.getString("data");
                    showdialog_eva(recordId);
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }


    private String[] item = {"好", "良", "中", "差", "暂不评价"};
    int index;

    public void showdialog_eva(final String recordId) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(mContent);
        builder.setTitle("请选择");
        builder.setCancelable(false);
        builder.setSingleChoiceItems(item, index, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                index = which;
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
//                Toast.makeText(context, "选择了" + item[index], Toast.LENGTH_SHORT).show();

                switch (item[index]) {
                    case "好":
                        PostPrestoreEva(recordId, "GOOD");
                        break;
                    case "良":
                        PostPrestoreEva(recordId, "WELL");
                        break;
                    case "中":
                        PostPrestoreEva(recordId, "MIDDLE");
                        break;
                    case "差":
                        PostPrestoreEva(recordId, "BAD");
                        break;
                    case "暂不评价":
                        PostPrestoreEva(recordId, "");
                        break;
                }

            }
        });
//        builder.setNegativeButton("取消", null);
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    /**
     * 预存评价
     */
    private void PostPrestoreEva(String recordId, String evaluateStatus) {
        String url = API.PostPrestoreEva + recordId;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数

        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("recordId", recordId);
        params.addFormDataPart("evaluateStatus", evaluateStatus);

        HttpRequest.post(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    ToastUtils.getInstanc(mContent).showToast("谢谢评价");
                    handler.removeCallbacks(runtier);

                    intiData();
                } else {

                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });

    }


    /**
     * 获取我的预存信息
     */
    private void GetMineprestore() {
        String url = API.GetMineprestore + MainActivity.userid;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("userId", MainActivity.userid);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    totalPoint = data.getInteger("totalPoint");
                    tv_totalPoint.setText("" + totalPoint);
                    listprestore.clear();
                    listprestore.addAll(JSONObject.parseArray(data.getString("merchantList"), MinePrestoreItem.class));
                    prestoreAdapter.notifyDataSetChanged();
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler = null; //此处在activity退出时及时 回收
    }

}
